/**
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/pageTitle'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { title } from '@/config'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // 交建局
  if (router.currentRoute.value.params.pageId == 'jjj') next()

  const whiteList = [] // 白名单列表(路由名称)
  if (whiteList.includes(to.name)) {
    next()
    return
  }

  const hasToken = store.getters['user/accessToken']
  const userInfo = store.getters['user/userInfo']

  if (!hasToken) {
    // 无token 跳转登录
    store.dispatch('user/goToLogin')
    next()
  } else {
    // 判断是否获取用户信息
    if (!userInfo.userId) {
      await store.dispatch('user/getUserInfo')
      const accessRoutes = await store.dispatch('routes/setRoutes')
      accessRoutes.forEach(item => {
        router.addRoute(item)
      })
      next()
    } else {
      next()
    }
  }
  NProgress.done()
})
var loading = document.getElementsByClassName('loading-wrapper')[0]
router.afterEach(to => {
  if (to.params.pageId == 'jjj') document.title = '江苏交建施工管控运行平台'
  else {
    const prefix = {
      yxjcgl: '运行监测-',
      yxjcgs: '运行监测-',
      zdcl: '重点车辆-'
    }
    document.title = `${prefix[to.params.pageId] || ''}${title}`
  }

  // 删除loading
  if (loading) {
    loading.remove()
    loading = null
  }
  NProgress.done()
})
